const { ipcMain, BrowserWindow } = require('electron')

// 主进程接收事件
ipcMain.handle('on-url-event', async (e, url) => {
  const res = await getSource(url)
  return res
})

// 通过url获取网站资源
function getSource(url) {
  return new Promise((resolve, reject) => {
    // 创建新窗口
    const win = new BrowserWindow({
      width: 1300,
      height: 800,
      show: false,
      webPreferences: {
        // 不在页面构建，在内存中运行
        offscreen: true
      }
    })

    win.loadURL(url)

    // 抓取页面加载完之后
    win.webContents.on('did-finish-load', async () => {
      // 获取抓取页面得标题
      const title = win.getTitle()
      try {
        // 截取网页主页图片(nativeImage)
        const image = await win.webContents.capturePage()
        if (!image.isEmpty()) {
          const screenImg = image.toDataURL()
          resolve({
            title,
            screenImg,
            url
          })
        } else {
          resolve({
            msg: '无法访问该站点'
          })
        }
      } catch (error) {
        reject(error)
      }
    })
  })
}
